import { Button, Form, Dialog } from '@alifd/next';
import { t } from '@lingui/macro';
import React, { useRef, useState, useEffect } from 'react';
import DrawerFooter from '@/components/DrawerFooter';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useStore } from '@/hooks';
import { FieldsGrid } from '../stores/definitions';

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 16,
  },
  style: { marginBottom: 20 },
};

const ViewNotify = ({ notify, modal, onCancel, onSubmit, ...formProps }) => {
  const [formData] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current;
  const { notifyStore: store } = useStore();

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      const res = await store.get(notify.id);
      _.assign(formData, res);
    })();
  }, []);

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('...errors', errors);
      return;
    }
    onSubmit?.(formData);
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      colon
      isPreview={false}
      {...formProps}
      value={formData}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <FieldsGrid
        formData={formData}
        itemLayout={{ ...formItemLayout, labelAlign: 'left' }}
        mode={modal[0]}
        columns={1}
        fields={['id', 'subject', 'content', 'businessKey', 'status', 'type', 'sendTypes', 'params']}
      />
      <DrawerFooter>
        <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>
        <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
      </DrawerFooter>
    </Form>
  );
};

export default observer(ViewNotify);
